@using CleanArchitecture.Blazor.Application.Features.Employees.Commands.AddEdit
@using SixLabors.ImageSharp
@using SixLabors.ImageSharp.Formats
@using SixLabors.ImageSharp.Processing
@inherits MudComponentBase
@inject IStringLocalizer<Employees> L
<MudDialog>
    <DialogContent>
        <MudForm Model="model" @ref="form" Validation="@(modelValidator.ValidateValue)">
            <MudGrid Justify="Justify.Center" Style="display:flex;">
                <MudItem sm="12" xs="12">
                    <div class="d-flex justify-center">

                        @if (string.IsNullOrEmpty(model.Avatar))
                        {
                            <MudElement Class="d-flex flex-column  align-center">
                                <MudAvatar Style="height:128px; width:128px; font-size:2rem;">@model.Name?.First()</MudAvatar>
                            </MudElement>
                        }
                        else
                        {
                            <MudElement Class="d-flex flex-column  align-center">
                                <MudAvatar Image="@model.Avatar" Style="height:128px; width:128px; font-size:2rem;" />
                            </MudElement>
                        }
                        <MudTooltip Text="@L["Click upload a photo."]">
                            <InputFile id="UploadPhoto" OnChange="UploadPhoto" hidden accept=".jpg, .jpeg, .png" />
                            <MudIconButton HtmlTag="label"
                                           Color="MudBlazor.Color.Info"
                                           Icon="@Icons.Filled.PhotoCamera"
                                           for="UploadPhoto"></MudIconButton>
                        </MudTooltip>
                    </div>
                </MudItem>
                <MudItem xs="12" sm="6">
                    <MudTextField Label="@L["Name"]" @bind-Value="model.Name"
                                  For="@(() => model.Name)"
                                  Required="true"
                                  RequiredError="@L["employee name is required!"]">
                    </MudTextField>
                </MudItem>
                <MudItem xs="12" sm="6">
                    <DepartmentAutocomplete @bind-Value="model.DepartmentId"
                                            For="@(() => model.DepartmentId)"
                                            Label="@L["Select Department"]"
                                            Placeholder="@L["Select Department"]"
                                            Required="true"
                                            RequiredError="@L["department is required!"]"
                                            Clearable="true"
                                            >
                    </DepartmentAutocomplete>
                </MudItem>
                <MudItem xs="12" sm="6">
                    <MudTextField Label="@L["Phone Number"]"
                                  Required="true"
                                  RequiredError="@L["phone number is required!"]"
                                  For="@(() => model.PhoneNumber)"
                                  @bind-Value="model.PhoneNumber"></MudTextField>
                </MudItem>
                <MudItem xs="12" sm="6">
                    <MudTextField Label="@L["Email"]"
                                  Required="true"
                                  RequiredError="@L["email is required!"]"
                                  For="@(() => model.Email)"
                                  @bind-Value="model.Email"></MudTextField>
                </MudItem>
                <MudItem xs="12" sm="6">
                    <PicklistAutocomplete Picklist="Picklist.Gender"
                                          Label="@L["Gender"]"
                                          For="@(() => model.Gender)"
                                          ResetValueOnEmptyText="true"
                                          @bind-Value="model.Gender"></PicklistAutocomplete>
                </MudItem>
                <MudItem xs="12" sm="6">
                    <DesignationAutocomplete @bind-Value="model.DesignationId"
                                            For="@(() => model.DesignationId)"
                                            Label="@L["Select Designation"]"
                                            Placeholder="@L["Designation"]"
                                            Clearable="true"
                                            >
                    </DesignationAutocomplete>
                </MudItem>
                 <MudItem xs="12">
                    <MudTextField Label="@L["About"]"
                                  Lines="2"
                                  For="@(() => model.About)"
                                  @bind-Value="model.About"></MudTextField>
                </MudItem>
            </MudGrid>
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">@L["Cancel"]</MudButton>
        <MudButton Color="MudBlazor.Color.Primary" OnClick="Submit">@L["Ok"]</MudButton>
    </DialogActions>
</MudDialog>

@code {
    MudForm form = default!;
    [CascadingParameter]
    MudDialogInstance MudDialog { get; set; } = default!;
    [Inject] private IUploadService _uploadService { get; set; } = default!;
    AddEditEmployeeCommandValidator modelValidator = new AddEditEmployeeCommandValidator();
    [EditorRequired][Parameter] public AddEditEmployeeCommand model { get; set; } = default!;


    private IList<string>? _prictures = null;

    private async Task UploadPhoto(InputFileChangeEventArgs e)
    {
        var filestream = e.File.OpenReadStream();
        var imgstream = new MemoryStream();
        await filestream.CopyToAsync(imgstream);
        imgstream.Position = 0;
        using (var outStream = new MemoryStream())
        {
            using (var image = Image.Load(imgstream, out IImageFormat format))
            {
                image.Mutate(
                   i => i.Resize(new ResizeOptions() { Mode = ResizeMode.Crop, Size = new SixLabors.ImageSharp.Size(128, 128) }));
                image.Save(outStream, format);
                var filename = e.File.Name;
                var fi = new FileInfo(filename);
                var ext = fi.Extension;
                var result = await _uploadService.UploadAsync(new UploadRequest()
                    {
                        Data = outStream.ToArray(),
                        FileName = Guid.NewGuid().ToString() + ext,
                        Extension = ext,
                        UploadType = UploadType.EmployeePicture
                    });
                model.Avatar = result;
                //Do your validations here
                Snackbar.Add($"{L["Upload photo successfully"]}", MudBlazor.Severity.Info);
            }
        }
    }
    async Task Submit()
    {
        await form.Validate();
        if (form.IsValid)
        {
            MudDialog.Close(DialogResult.Ok(true));
        }

    }
    void Cancel() => MudDialog.Cancel();
}
